import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class SingletonClientHandle extends ChannelInboundHandlerAdapter {

    private List<ChannelHandlerContext> ctxData = new CopyOnWriteArrayList<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        if (ctxData.size() < 1) {
            ctxData.add(ctx);
        }
        for (ChannelHandlerContext ctxDatum : ctxData) {
            if (ctxDatum.channel().hashCode() != ctx.channel().hashCode()) {
                ctxData.add(ctx);
            }
        }
        System.out.println("connetted");
//        ctx.channel().writeAndFlush("hi, nice to see you");
        System.out.println("in bound " + ctx.channel().toString() + ctx.channel().remoteAddress());
        ctx.writeAndFlush("hi, nice to see you");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println(msg.toString() + "from server:" + ctx.channel().remoteAddress());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//        String msg = "my data is here: " + new Date();
//        ctx.writeAndFlush(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    public List<ChannelHandlerContext> getCtxData() {
        return ctxData;
    }

    public void setCtxData(List<ChannelHandlerContext> ctxData) {
        this.ctxData = ctxData;
    }
}
